package com.qq.mobilemanager.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import net.youmi.android.AdManager;
import net.youmi.android.offers.OffersManager;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qq.mobilesafe.R;
import com.qq.mobilesafe.db.dao.AntivirusDao;
import com.qq.mobilesafe.domain.ApkInfo;
import com.qq.mobilesafe.domain.Virus;
import com.qq.mobilesafe.manager.ThreadManager;
import com.qq.mobilesafe.utils.GsonTools;
import com.qq.mobilesafe.utils.PackageUtils;

public class WelcomeActivity extends Activity {

	@ViewInject(R.id.tv_splash_version)
	private TextView tv_version;
	@ViewInject(R.id.rl_splash)
	private RelativeLayout rl_splash;

	@ViewInject(R.id.tv_progress)
	private TextView tv_progress;

	private String versionName;
	private int versionCode;

	private String Desc;
	private String DownloadUrl;
	private AntivirusDao dao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 有米广告初始化
		AdManager.getInstance(this).init("4b2db6d8c67b8eec",
				"5775c5ae80f21417", true);
		OffersManager.getInstance(this).onAppExit();

		initView();
		// 渐变动画效果
		AlphaAnimation animation = new AlphaAnimation(0.3f, 1f);
		animation.setDuration(2000);
		rl_splash.startAnimation(animation);
	}

	private void initView() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_splash);
		ViewUtils.inject(this);
		copyDB("address.db");
		copyDB("antivirus.db");
		tv_version.setText("版本号：" + PackageUtils.getVersionName(this));

		versionCode = PackageUtils.getVersionCode(this);

		checkVersion();

	}

	// 检查版本号
	private void checkVersion() {

		String url = "http://192.168.25.25/info.json";
		HttpUtils http = new HttpUtils(2000);
		http.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				arg0.printStackTrace();

				enterHome();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				processData(arg0.result);
			}
		});
	}

	// 解析json
	protected void processData(String result) {

		ApkInfo apkInfo = GsonTools.changeGsonToBean(result, ApkInfo.class);
		DownloadUrl = apkInfo.downloadurl;
		Desc = apkInfo.desc;
		int netVersion = apkInfo.version;
		if (netVersion == versionCode) {
			enterHome();
		} else {
			showDialog();
		}

		// try {
		// JSONObject json = new JSONObject(result);
		//
		// DownloadUrl = json.getString("downloadurl");
		//
		// Desc = json.getString("desc");
		//
		// int netVersion = json.getInt("version");
		// if (netVersion == versionCode) {
		// enterHome();
		// } else {
		// showDialog();
		// }
		// } catch (JSONException e) {
		// e.printStackTrace();
		// enterHome();
		// }

	}

	// 显示对话框
	private void showDialog() {
		Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage(Desc);

		// 返回键，取消的监听
		builder.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface arg0) {
				enterHome();
			}
		});

		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				enterHome();
				dialog.dismiss();
			}
		});

		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				downLoadApk(DownloadUrl);
				dialog.dismiss();

			}
		});
		builder.show();
	}

	// 下载更新包
	protected void downLoadApk(String url) {
		// 设置连接超时
		HttpUtils httpUtils = new HttpUtils(3000);

		httpUtils.download(url, "/mnt/sdcard/temp.apk",
				new RequestCallBack<File>() {

					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						installApk("/mnt/sdcard/temp.apk");
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						arg0.printStackTrace();

					}
				});

	}

	// 安装软件
	protected void installApk(String url) {

		Intent intent = new Intent();
		intent.setAction("android.intent.action.View");
		intent.addCategory("android.intent.category.DEFAULT");

		intent.setDataAndType(Uri.fromFile(new File(url)),
				"application/vnd.android.package-archive");
		startActivityForResult(intent, 0);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		enterHome();
		super.onActivityResult(requestCode, resultCode, data);

	}

	// 进入主界面
	private void enterHome() {
		startActivity(new Intent(this, GuideActivity.class));
		finish();
	}

	private void copyDB(final String dbName) {
		// File filesDir = getFilesDir();
		// System.out.println("路径:" + filesDir.getAbsolutePath());
		ThreadManager.getInstance().createShortPool().execute(new Runnable() {

			@Override
			public void run() {
				File destFile = new File(getFilesDir(), dbName);// 要拷贝的目标地址

				if (destFile.exists()) {
					System.out.println("数据库" + dbName + "已存在!");
					return;
				}

				FileOutputStream out = null;
				InputStream in = null;

				try {
					in = getAssets().open(dbName);
					out = new FileOutputStream(destFile);

					int len = 0;
					byte[] buffer = new byte[1024];

					while ((len = in.read(buffer)) != -1) {
						out.write(buffer, 0, len);
					}

				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						in.close();
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	private void updateVirus() {

		dao = new AntivirusDao();
		HttpUtils httpUtils = new HttpUtils();
		String url = "http://192.168.13.126:8080/virus.json";
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {

				Virus virus = GsonTools.changeGsonToBean(arg0.result,
						Virus.class);

				dao.addVirus(virus.md5, virus.desc);

			}
		});
	}
}
